package com.changgou.system.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

/**
 * @author 戴金华
 * @date 2019-12-19 11:22
 */
public class JwtUtil {

    //有效时间
    private static final long JWT_TTL = 3600000L;       //60*60*1000 一个小时

    //设置密钥的明文
    public static final String JWT_KEY = "itcast";

    /**
     * 创建token
     *
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createToken(String id, String subject, Long ttlMillis) {


        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis==null){
            ttlMillis = JwtUtil.JWT_TTL;
        }

        long expMillis = nowMillis+ttlMillis;

        Date expDate = new Date(expMillis);
        SecretKey secretKey = generalKey();
        System.out.println("生成令牌用的签名是:"+secretKey);
        JwtBuilder build = Jwts.builder().setId(id)      //唯一的id
                .setSubject(subject)    //主题 可以是json数据
                .setIssuer("admin")     //令牌的签发者
                .setIssuedAt(now)       //设置签发时间
                .signWith(signatureAlgorithm, secretKey)       //使用HS256对称加密算法 第二个单数为密钥
                .setExpiration(expDate);
        return build.compact();
    }


    /**
     * 生成加密后的密钥 secretKey
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodeKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKeySpec key = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return key;
    }

    public static void main(String[] args) {
//        String token = createToken("10086", "测试创建token令牌", null);

        //解析令牌
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDA4NiIsInN1YiI6Iua1i-ivleWIm-W7unRva2Vu5Luk54mMIiwiaXNzIjoiYWRtaW4iLCJpYXQiOjE1NzY3MjcxOTIsImV4cCI6MTU3NjczMDc5Mn0.dA8qPMzS4CxCIet5rdi75jOhy34FjTfS9v-Dq6DqF9k";
        String publicKey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjgM8AXx70VOGvZD6XfG/zb8ocvwLVp7QB+ejYRhrVQfV/R86ddfyLOkJpHaRhxEssuQhe+D01kiDd2S2NmjJmuLSA3kYoMJORv7nqrJ7Kw1pnv9O6UFQ769TtGLfHXBQz/ISybZSA9TPktUYOt3jSXO0cUUb12aQUprjuGu3ex9Iu6RmtPIBwS9c08NOOAXzhXJ7PsGraiU83xC/WufuKGkG4xF+ucBbbrXIQQl7k6YEmxUwzHSefN4o1zv3rGlcUVOEqmKZdOk3dgg7zb9x969SrSHBYvU4v37oc01ueF1yHW6I/ax38NAndbGfPOPH5OjS0G3PEOuLDgcvEfTsFQIDAQAB-----END PUBLIC KEY-----";
        Claims claims = Jwts.parser().setSigningKey("itcast").parseClaimsJws(token).getBody();
        System.out.println(claims);
    }
}
